package LinkedList.两数相加2;

import LinkedList.ListNode;

public class Test {
    public ListNode reverse(ListNode head) {
        ListNode prve = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = prve;
            prve = cur;
            cur = next;
        }
        return prve;
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;

        l1 = reverse(l1);
        l2 = reverse(l2);

        int n = 0; // 进位的数
        while(l1 != null || l2 != null || n != 0) {
            int valL1 = l1 == null ? 0 : l1.val;
            int valL2 = l2 == null ? 0 : l2.val;
            int sum = valL1 + valL2 + n;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
            n = sum / 10;
        }

        dummy.next = reverse(dummy.next);

        return dummy.next;
    }
}
